from re import I
from views.base import BaseHandler
from db import db
from util.comm import md5
class IndexHandler(BaseHandler):
    def get(self):
        roleid=1
        sql="select res.*,pres.name as pname from role_resource as rr left join resource as res " \
            "on rr.resourceid=res.id  inner join resource as pres on res.pid=pres.id where rr.roleid=%d and res.type=1"%(int(roleid))
        res = db.find_all(sql)

        reslist=[]
        ids=[]
        #遍历查询结果
        for i in res:
            #判断父类是否存在，不存在添加
            if i["pid"] not in ids:
                ids.append(i['pid'])
                reslist.append({"id":i["pid"],"name":i['pname'],"son":[{"id":i['id'],"name":i['name'],'url':i['url']}]})
            else:
                #存在，查找父类，遍历父类用子类的pid对比
                for (index,p) in enumerate(reslist):
                    if i['pid'] == p['id']:
                        #将子类加到父类下
                        reslist[index]['son'].append({"id":i['id'],"name":i['name'],'url':i['url']})
        data={"code":200,"menulist":reslist}
        self.write(data)